<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="loginName">
      <el-input v-model="loginForm.loginName" clearable :placeholder="$t('login.loginName')">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        clearable
        type="password"
        :placeholder="$t('login.password')"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> {{ $t("login.resettext") }} </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      {{ $t("login.submittext") }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/types/base";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { useI18n } from "vue-i18n";
import { BusinessType, BusinessOptType } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";
import { encrypt } from "@/api/services/encrypt";
import { useUserStore } from "@/stores/modules/user";
import { useDataStore } from "@/stores/modules/data";

const dataStore = useDataStore();
const { addUserAction } = useUserAction(BusinessType.LOGIN);
const { t } = useI18n();

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

const defaultAccount = JSON.parse(import.meta.env.VITE_DEFAULT_ACCOUNT);

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  loginName: [{ required: true, message: t("login.userNameInputHint"), trigger: "blur" }],
  password: [{ required: true, message: t("login.passwordInputHint"), trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  loginName: defaultAccount.loginName,
  password: defaultAccount.password
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      let params = { ...loginForm, password: encrypt(loginForm.password, loginForm.loginName) };
      loginApi(params)
        .then(async res => {
          let loginInfo = { password: params.password, userName: params.loginName };
          let ss = window.btoa(unescape(encodeURIComponent(JSON.stringify(loginInfo))));
          userStore.setParam(ss);
          userStore.setToken(res.data.token);
          userStore.setUserInfo(res.data);
          dataStore.userId = res.data.token;

          // 2.添加动态路由
          await initDynamicRouter();

          // 3.清空 tabs、keepAlive 数据
          tabsStore.setTabs([]);
          keepAliveStore.setKeepAliveName([]);

          // 4.跳转到首页
          router.push(HOME_URL);
          ElNotification({
            title: getTimeState(),
            message: `${t("home.welcome")} EasyWork`,
            type: "success",
            duration: 3000
          });

          // 5.记录登录日志
          addUserAction(res.data.loginName, BusinessOptType.LOGIN, "成功");
        })
        .catch(err => {
          console.log(err);
          if (err === "No permission") {
            console.log("当前用户无权限，请联系管理员配置权限");
          } else {
            ElNotification({
              title: "登录提示",
              message: err.message,
              type: "error",
              duration: 3000
            });
          }
        });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (loginFormRef: FormInstance | undefined) => {
  if (!loginFormRef) return;
  loginFormRef.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
@/api/types
